/**
 * @file aicl_mem_001.cpp
 *
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2018. All rights reserved.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <stdio.h>
#include <math.h>
#include <ctime>
#include <chrono>

#include "acl/acl.h"
#include "aicl.h"
#include "utils.h"

int main()
{
    int32_t deviceId = 0;
    void *dBuffer1 = nullptr;
    void *dBuffer2 = nullptr;
    void *dBuffer3 = nullptr;
    size_t copy_len = 1024 * 1024 * 1024; // 1M
    aiclRet ret1 = 0;
    aiclRet ret2 = 0;
    aiclRet ret3 = 0;
    
    const char *workPath = getenv("OPENCANN_TPATH");
    if (workPath == NULL) {
        ERROR_LOG("OPENCANN_TPATH is not set");
        return OPENCANN_FAILED;
    }
    std::string configPath = workPath;
    configPath += "/common/test_data/config/init_config.json";
    // config file
    if (aiclInit(configPath.c_str()) != AICL_RET_SUCCESS) {
        ERROR_LOG("aiclInit config failed");
        return OPENCANN_FAILED;
    }

    if (aiclrtSetDevice(deviceId) != AICL_RET_SUCCESS) {
        ERROR_LOG("Set device[%d] failed.", deviceId);
        return OPENCANN_FAILED;
    }

    if (aiclrtMalloc(&dBuffer1, copy_len, AICL_MEM_MALLOC_HUGE_FIRST) != AICL_RET_SUCCESS) {
        ERROR_LOG("rtMalloc MEM_MALLOC_HUGE_FIRST failed");
        return OPENCANN_FAILED;
    } else {
        INFO_LOG("rtMalloc MEM_MALLOC_HUGE_FIRST success");
    }

    if (aiclrtMalloc(&dBuffer2, copy_len, AICL_MEM_MALLOC_HUGE_ONLY) != AICL_RET_SUCCESS) {
        ERROR_LOG("rtMalloc MEM_MALLOC_HUGE_ONLY failed");
        return OPENCANN_FAILED;
    } else {
        INFO_LOG("rtMalloc MEM_MALLOC_HUGE_ONLY success");
    }

    if (aiclrtMalloc(&dBuffer3, copy_len, AICL_MEM_MALLOC_NORMAL_ONLY) != AICL_RET_SUCCESS) {
        ERROR_LOG("rtMalloc MEM_MALLOC_NORMAL_ONLY failed");
        return OPENCANN_FAILED;
    } else {
        INFO_LOG("rtMalloc MEM_MALLOC_NORMAL_ONLY success");
    }

    ret1 = aiclrtFree(dBuffer1);
    ret2 = aiclrtFree(dBuffer2);
    ret3 = aiclrtFree(dBuffer3);
    if (ret1 != AICL_RET_SUCCESS || ret2 != AICL_RET_SUCCESS || ret3 != AICL_RET_SUCCESS) {
        ERROR_LOG("rtFree  failed");
        return OPENCANN_FAILED;
    } else {
        INFO_LOG("rtFree success");
    }

    // aiclFinalize
    if (aiclFinalize() != AICL_RET_SUCCESS) {
        ERROR_LOG("aiclFinalize failed");
        return OPENCANN_FAILED;
    }
    return OPENCANN_SUCCESS;
}
